import {Map, View, Image, ScrollView} from '@tarojs/components';
import {AtTabs, AtTabsPane} from 'taro-ui';
import Taro from '@tarojs/taro';
import {connect} from '@tarojs/redux';
import {request, unite, appConfig} from "../../../utils/index";
import SelectList from "../../../components/select-list/selectList";
import './map.scss';
import Go from "../../../asset/images/go.png";
import Flag from "../../../asset/images/flag.png";
import Point from "../../../asset/images/point.png";
import My from "../../../asset/images/my.png";
import Hui from "../../../asset/images/hui.png";
import none from "../../../asset/images/none.png";

class MapBox extends Taro.Component {
    config = {
        navigationBarTitleText: '门店'
    };

    state = {
        latitude: 0, //经度
        longitude: 0, //纬度
        adcodes: 0, //地址名称

        classDate: '', //课程日期，格式yyyy/mm/dd
        classScaleId: -1, //团课规模ID
        classTypeId: -1, //课程类型ID
        periodId: -1, //时间段区间ID
        priceId: -1, //	价格区间ID
        regionId: 340102, //区域ID

        markers:[], //map组件markers的参数
        id: null, //选取教室id
        listDataWrap: [],
        listData: [], //列表数据
        is_type: false, //false 回弹列表 true 打开列表
        roomListData: [], //课程列表

        current: 0,
    };

    temp = {
        loading: false //防止多次点击
    };

    componentWillMount() {
        const option = this.$router.params;
        console.log(option.timer);
        this.setState({
            latitude: option.latitude, //赋值经度
            longitude: option.longitude, //赋值纬度
            adcodes: option.adcode, //赋值地址名称
            regionId: option.regionId,
            classDate: option.timer, //初始化课程需要初始时间
        },()=>{
            this.init();
        })
    };

    //在 componentWillMount后执行
    componentDidMount() {
        //创建 map 上下文 MapContext 对象
        this.mapCtx = Taro.createMapContext("shopMap");
    };

    //获取商家位置
    init = () => {
        const {classScaleId, classTypeId, periodId, priceId, regionId, latitude, longitude} = this.state;
        if (this.temp.loading) return; //防止多次点击
        this.temp.loading = true;
        const params = {
            url: '/wx/firstPage/getNearByRoomList',
            data:{
                classScaleId, //团课规模ID
                classTypeId, //课程类型ID
                distance: '10', //与当前位置距离（单位km）
                latitude,
                longitude,
                // latitude: 26.026014955115276,
                // longitude: 119.29837137705749,
                periodId, //时间段区间ID
                priceId, //价格区间ID
                regionId, //区域ID
                queryType: 2, //根据区域ID查询的时候为1，根据经纬度查询的时候为2）
            }
        };
        request(params, false).then(res => {
            this.temp.loading = false; //防止多次点击
            if (res) {
                if (res.code == 200) {
                    Taro.hideLoading();
                    if (res && res.data) {
                        let ary = [];
                        if (res.data.length != 0) {
                            ary = res.data.map((item) => {
                                let maker = {
                                    alpha: "1", //标注的透明度
                                    height: 60, //标注图标高度
                                    width: 60, //标注图标宽度
                                    // iconPath: flag,
                                    iconPath: 'https://pic.pmad.com.cn/healthy/class/%E9%97%A8%E5%BA%97%E5%AE%9A%E4%BD%8D.png', //显示的图标   true的都为C享
                                    label:{
                                        anchorX: -24, //label的坐标，原点是 marker 对应的经纬度
                                        anchorY: 1, //label的坐标，原点是 marker 对应的经纬度
                                        bgColor: "#fff", //背景色
                                        borderColor: "#494948", //边框颜色
                                        borderRadius: 2, //边框圆角
                                        borderWidth: 1, //边框宽度
                                        color: "#676765", //文本颜色
                                        fontSize: 10, //文字大小
                                        padding: 2, //文本边缘留白
                                        textAlign: "center" //文本对齐方式。有效值: left, right, center
                                    }
                                };
                                maker.label.content = item.roomName; //文本(商店名称)
                                maker.id = item.roomId; //标记点 id
                                maker.latitude = item.latitude; //店铺经度
                                maker.longitude = item.longitude; //店铺维度
                                return maker;
                            });
                            this.setState({
                                markers: ary,
                                listDataWrap: res.data,
                                id: res.data[0].roomId,
                            },() => {
                                this.markerTap({markerId: res.data[0].roomId})
                            })
                        } else {
                            this.setState({
                                markers: ary,
                                listDataWrap: res.data,
                                id: null
                            })
                        }
                    }
                }
            }
        })
    };

    //点击跳转到相对应的店铺
    markerTap = e => {
        const {listDataWrap, markers} = this.state;
        const option = this.$router.params;
        let data = [];
        listDataWrap.forEach((item) => {
            if (item.roomId == e.markerId) {
                data = {
                    avatar: item.avatar, //教室图片
                    roomName: item.roomName, //教室名称
                    address: item.address, //地址
                    describeInfo: item.describeInfo,//教室介绍
                    id: item.roomId,
                    collectionStatus: item.collectionStatus, //收藏状态（0 未收藏、1 已收藏）
                    latitude: item.latitude,
                    longitude: item.longitude,
                }
            }
        });
        markers.forEach((item, index) => {
            if (item.id == e.markerId) {
                this.setState(prevState => {
                    markers[index].height = 80;
                    markers[index].width = 80;
                    return {
                        markers: prevState.markers
                    }
                }, () => {
                    console.log(JSON.stringify(this.state.markers) + '123')
                })
            } else {
                this.setState(prevState => {
                    markers[index].height = 60;
                    markers[index].width = 60;
                    return {
                        markers: prevState.markers
                    }
                })
            }
        });
        this.setState({
            classDate: option.timer,
            id: e.markerId,
            listData: data,
        }, () => {
            this.getclassRoomList(data.id);
        })
    };

    getTypes = (item) => {
        console.log('zhao');
        const {regionId} = this.state;
        this.setState({
            classScaleId: Number(item.selectList) || -1, //1v1
            periodId: Number(item.tgTypeId) || -1, //时间段
            regionId: Number(item.regionId) || regionId, //地区
            classTypeId: Number(item.classTypeId) ||-1, //课程类型
            priceId: Number(item.moneyId) || -1, //价格id
            id: null,
        }, () => {
            this.init() //获取课程列表
        })
    };

    //跳转到教室详情页
    skipDetail = (id) => {
        Taro.navigateTo({
            url: '../classroom-detail/classroomDetail?id=' + id,
        })
    };

    //跳转教室地图导航
    goToMap = (e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        const {listData} = this.state;
        console.log(listData);
        if (listData.latitude) {
            Taro.openLocation({
                latitude: Number(listData.latitude),
                longitude: Number(listData.longitude),
                name: listData.roomName,
                address: listData.address
            })
        } else {
            unite.showToast('该店铺暂无经纬度');
        }
    };

    //收藏 取消收藏
    collect = () => {
        const {listData} = this.state;
        if (listData.collectionStatus == 0) {
            const params = {
                url: '/wx/collection/save',
                data:{
                    collectionTypeCode: '03', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: listData.id,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        this.setState(prevState => {
                            listData.collectionStatus = 1;
                            return{
                                listData: prevState.listData
                            }
                        })
                        unite.showToast('收藏成功');
                        this.init() //获取课程列表
                    }
                }
            })
        } else {
            const params = {
                url: '/wx/collection/deleteById',
                data:{
                    collectionTypeCode: '03', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: listData.id,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        this.setState(prevState => {
                            listData.collectionStatus = 0;
                            return{
                                listData: prevState.listData
                            }
                        })
                        unite.showToast('已取消收藏');
                        this.init() //获取课程列表
                    }
                }
            })
        }
    };

    // //回归原来的位置
    clickcontrol = () => {
        const option = this.$router.params;
        this.setState({
            latitude: option.latitude, //赋值经度
            longitude: option.longitude, //赋值纬度
            adcode: option.adcode //赋值地址名称
        },()=>{
            let ctx = Taro.createMapContext("shopMap");
            ctx.moveToLocation();
            this.init();
        })
    };

    // 移动地图重新获取附近商家
    regionchange = e => {
        console.log(e)
        // 地图发生变化的时候，获取中间点，也就是用户选择的位置toFixed   
        if (e.type == 'end' && e.causedBy == 'drag') {
            this.mapCtx.getCenterLocation({
                type: 'gcj02',
                success: (res) => {
                    if(res.latitude === this.state.latitude && res.longitude === this.state.longitude) return;
                    this.setState({
                        latitude: res.latitude,
                        longitude: res.longitude,
                    },()=>{
                        Taro.showLoading({
                            title: '加载中…'
                        });
                        this.init();
                    })
                }
            })
        }
    };

    //获取课程列表
    getclassRoomList = (id) => {
        const {classDate} = this.state;
        const params = {
            url: '/wx/firstPage/getRoomDetail',
            data:{
                classDate,
                roomId: id
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            roomListData: res.data.hotClasses //获取课程列表
                        })
                    }
                }
            }
        })
    };

    //false 回弹列表 true 打开列表
    openList = () => {
        this.setState(prevState => ({
            is_type: !prevState.is_type
        }));
    };

    //时间筛选
    getTimers = (time, index) => {
        this.setState({
            classDate: time,
            current: index,
        }, () => {
            const {listData} = this.state
            this.getclassRoomList(listData.id);
        });
    };

    tabsClick = (is) => {
        const {getData} = this.props;
        let timer = getData.weekDays;
        this.setState({
            current: is,
            classDate: timer[is].classDate
        }, () => {
            const {listData} = this.state
            this.getclassRoomList(listData.id);
        });
    };

    //跳转教室列表
    skipClassList = () => {
        console.log(this.$router.params);
        Taro.navigateTo({
            url: '../classroom-list/classroomList?timer=' + this.$router.params.timer
        })
    };

    //跳转课程详情
    skipCourseDetail = (classId, dispatchId) => {
        Taro.navigateTo({
            url: '../course-detail/courseDetail?classId=' + classId + '&dispatchId=' + dispatchId,
        })
    };

    render() {
        const {latitude, longitude, markers, id, listData, is_type, roomListData, classDate, current, listDataWrap} = this.state;
        const {getData} = this.props;
        return (
            <View>
                {!is_type &&(
                    <Map
                        id="shopMap"
                        className="shop-map"
                        latitude={latitude} //当前经度
                        longitude={longitude} //当前纬度
                        markers={markers} //标记点
                        scale={13}
                        showLocation //显示带有方向的当前定位点
                        // includePoints={markers}
                        onMarkerTap={this.markerTap} //点击标记点时触发
                        onLabelTap={this.markerTap}//点击label点时触发
                        onRegionChange={this.regionchange} //视野发生变化时触发
                    />
                )}
                <View className="shop-sort">
                    {!is_type &&(
                        <View className="restore-site">
                            {/*<View className="restore-site-wrap" onClick={this.skipClassList}>*/}
                            {/*    <View className="restore-text">列表</View>*/}
                            {/*</View>*/}
                            <View className="restore-site-wrap" onClick={this.clickcontrol}>
                                <Image className="site-img" src={Hui}/>
                            </View>
                        </View>
                    )}
                    <View className={`shop-sort-wrap ${is_type ? 'shop-sort-wrap-active' : ''}`}>
                        {/*<View className="sort-wrap-top flex-center" onClick={this.openList}>*/}
                        {/*    {is_type ? (*/}
                        {/*        <View className="sort-wrap-top-xia"> > </View>*/}
                        {/*    ) : (*/}
                        {/*        <View className="sort-wrap-top-heng"></View>*/}
                        {/*    )}*/}
                        {/*</View>*/}
                        {/*{id != null && listData &&(*/}
                        {/*    <View className="shop-sort-top">*/}
                        {/*        <View className="shop-sort-content" onClick={this.skipDetail}>*/}
                        {/*            <Image className="shop-sort-img" src={listData.avatar || appConfig.picurl+'/cam/assets/img/energy-ny/banner_head.png'}/>*/}
                        {/*            <View className="shop-sort-title">*/}
                        {/*                <View className="shop-sort-name">{listData.roomName}</View>*/}
                        {/*                <View className="shop-sort-address text-overflow">{listData.address}</View>*/}

                        {/*            </View>*/}
                        {/*            <View className="shop-sort-skip" onClick={this.goToMap}>*/}
                        {/*                <Image className="sort-skip-tb" src={Go}/>*/}
                        {/*                <View className="sort-skip-jl">去这里</View>*/}
                        {/*            </View>*/}
                        {/*        </View>*/}
                        {/*    </View>*/}
                        {/*)}*/}
                        {/*<SelectList getClassDate={classDate} onTimer={this.getTimers}/>*/}
                        <View className="sort-list-gd flex-lr">
                            <View>搜索结果</View>
                            <View className="flex-r" onClick={this.skipClassList}>
                                <View className="qb-js">全部教室</View>
                                <View className="arrow"></View>
                            </View>
                        </View>
                        <AtTabs className="com-tabs" current={current} tabList={getData.weekDays} onClick={this.tabsClick.bind(this)}>
                            {getData.length != 0 && getData.weekDays.map((va, ixs) => (
                                <AtTabsPane current={current} key={ixs} index={ixs+1} >
                                    <ScrollView
                                        className="content-view"
                                        scrollY
                                        upperThreshold={3}
                                        scroll-with-animation
                                        enhanced
                                        show-scrollbar
                                        paging-enabled
                                        fast-deceleration
                                        lowerThreshold={3}
                                    >
                                        <View className="classRoom-list-wrap">
                                            {listDataWrap && listDataWrap.map((item, index) => (
                                                <View className="shop-sort-content flex-top" key={index} onClick={this.skipDetail.bind(this,item.roomId)}>
                                                    <Image className="shop-sort-img" src={item.avatar || item.picurl+'/cam/assets/img/energy-ny/banner_head.png'}/>
                                                    <View className="xian-list-content flex-top">
                                                        <View className="shop-sort-title">
                                                            <View className="shop-sort-name">{item.roomName}</View>
                                                            <View className="shop-sort-address text-overflow">{item.address}</View>
                                                        </View>
                                                        <View className="shop-sort-skip" onClick={this.goToMap}>
                                                            <Image className="sort-skip-tb" src={Go}/>
                                                            <View className="sort-skip-jl">去这里</View>
                                                        </View>
                                                    </View>
                                                </View>
                                            ))}
                                            {/*{roomListData && roomListData.map((item, index) => (*/}
                                            {/*    <View className="classRoom-list flex-top" key={index}>*/}
                                            {/*        <Image className="room-img" src={item.avatar}/>*/}
                                            {/*        <View className="list-right flex-lr">*/}
                                            {/*            <View>*/}
                                            {/*                <View className="name">{item.className}</View>*/}
                                            {/*                <View className="flex-l">*/}
                                            {/*                    <View className="room-timer">{item.classBeginTime +'-'+item.classEndTime}</View>*/}
                                            {/*                    <View>¥{item.price}/节</View>*/}
                                            {/*                </View>*/}
                                            {/*                <View className="flex-l">*/}
                                            {/*                    <View className="list-top-left">{item.reservedInfo}</View>*/}
                                            {/*                    {item.labelNames.map((items, indexs) => (*/}
                                            {/*                        <View className="kepp-gg flex-center" key={indexs}>{items}</View>*/}
                                            {/*                    ))}*/}

                                            {/*                </View>*/}
                                            {/*            </View>*/}
                                            {/*            <View className="right-btn flex-center" onClick={this.skipCourseDetail.bind(this, item.classId, item.dispatchId)}>{item.reservedStatus == 0 ? '预约' : '已约满'}</View>*/}
                                            {/*        </View>*/}
                                            {/*    </View>*/}
                                            {/*))}*/}
                                            {(!listDataWrap || listDataWrap.length == 0) &&(
                                                <View className="none">
                                                    <Image src={none}/>
                                                    <View>暂无教室</View>
                                                </View>
                                            )}
                                        </View>
                                    </ScrollView>
                                </AtTabsPane>
                            ))}
                        </AtTabs>
                    </View>
                </View>
                {/*    锚点*/}
                {!is_type &&(
                    <Image src={Point} className="map-point" mode="aspectFit"/>
                )}
            </View>

        )
    }
}

const mapStateToProps = state => {
    let {mallCategory, getData} = state;
    return {
        mallCategory,
        getData
    }
};

export default connect(mapStateToProps, null)(MapBox);

